package com.jyw.activity;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.UserInfo;
import com.jyw.pojo.WXPayData;
import com.jyw.thirdparty.alipay.PayResult;
import com.kennyc.bottomsheet.BottomSheet;
import com.kennyc.bottomsheet.BottomSheetListener;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/9
 */

public class CzActivity extends BaseActivity implements View.OnClickListener {
    private IWXAPI api;
    private String WX_APP_ID = "wx301cb026f2a8e3ac";

    private LinearLayout layoutOnline;
    private FrameLayout layoutCard;
    private EditText editCard;
    private ImageView  ivOnlineOrCard;
    private TextView ivMinus, ivPlus,tvGo, tvCount, tvPhone, tvYue;
    private View vOnline, vCard;

    private boolean isOnline = true;
    private String orderID;

    // 商户PID
    public static final String PARTNER = " ";
    // 商户收款账号
    public static final String SELLER = " ";
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "\n" +
            " ";
    public static final String WX_SIGN = " ";
    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(CzActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(CzActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(CzActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, false);
        api.registerApp(WX_APP_ID);
        setContentView(R.layout.activity_cz);

        layoutOnline = (LinearLayout) findViewById(R.id.layout_online);
        layoutCard = (FrameLayout) findViewById(R.id.layout_card);
        editCard = (EditText) findViewById(R.id.edit_card);
        ivMinus = (TextView) findViewById(R.id.iv_minus);
        ivPlus = (TextView) findViewById(R.id.iv_plus);
        ivOnlineOrCard = (ImageView) findViewById(R.id.iv_online_or_card);
        tvGo = (TextView) findViewById(R.id.tv_go);
        tvCount = (TextView) findViewById(R.id.tv_count);
        tvPhone = (TextView) findViewById(R.id.tv_phone);
        tvYue = (TextView) findViewById(R.id.tv_yue);
        vOnline = findViewById(R.id.v_online);
        vCard = findViewById(R.id.v_card);

        ivMinus.setOnClickListener(this);
        ivPlus.setOnClickListener(this);
        tvGo.setOnClickListener(this);
        vOnline.setOnClickListener(this);
        vCard.setOnClickListener(this);
        findViewById(R.id.iv_back).setOnClickListener(this);

        loadUserInfo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.iv_minus:
                if (Integer.valueOf(tvCount.getText().toString()) == 1) {
                    Toast.makeText(CzActivity.this, "至少充值100元", Toast.LENGTH_SHORT).show();
                } else {
                    int oldCount = Integer.valueOf(tvCount.getText().toString());
                    tvCount.setText(String.valueOf(oldCount - 1));
                }
                break;
            case R.id.iv_plus:
                int oldCount = Integer.valueOf(tvCount.getText().toString());
                tvCount.setText(String.valueOf(oldCount + 1));
                break;
            case R.id.v_online:
                isOnline = true;
                layoutOnline.setVisibility(View.VISIBLE);
                layoutCard.setVisibility(View.INVISIBLE);
                ivOnlineOrCard.setImageResource(R.drawable.cz_0);
                break;
            case R.id.v_card:
                isOnline = false;
                layoutOnline.setVisibility(View.INVISIBLE);
                layoutCard.setVisibility(View.VISIBLE);
                ivOnlineOrCard.setImageResource(R.drawable.cz_1);
                break;
            case R.id.tv_go:
                if (!isOnline) {
                    cardGo();
                } else {
                    final BottomSheet sheet = new BottomSheet.Builder(CzActivity.this)
                            .setSheet(R.menu.zhifu)
                            .setTitle("请选择")
                            .setListener(new BottomSheetListener() {
                                @Override
                                public void onSheetShown(@NonNull BottomSheet bottomSheet) {
                                }

                                @Override
                                public void onSheetDismissed(@NonNull BottomSheet bottomSheet, @DismissEvent int i) {
                                }

                                @Override
                                public void onSheetItemSelected(@NonNull BottomSheet bottomSheet, MenuItem menuItem) {
                                    switch (menuItem.getItemId()) {
                                        case R.id.weixin:
                                            weixinGo();
                                            break;
                                        case R.id.zhifubao:
                                            alipayGo();
                                            break;
                                    }
                                }

                            }).create();
                    sheet.show();
                }
                break;
        }
    }

    private void alipayGo() {
        Request request = new Request.Builder().
                url(Server.GET_PAY_ORDERID + "?money=" + 100 * Integer.valueOf(tvCount.getText().toString())
                        + "&type=alipay").
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(CzActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                orderID = response.body().string();
                aliPay();
            }
        });
    }

    private void aliPay() {
        Request request = new Request.Builder().
                url(" "
                        + "?payid=alipay&type=alipay"
                        + "&order_id=" + orderID
                        + "&appid=dongyijs" + "&total=" + 100 * Integer.valueOf(tvCount.getText().toString())).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(CzActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String orderInfo = response.body().string();

                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        // 构造PayTask 对象
                        PayTask alipay = new PayTask(CzActivity.this);
                        // 调用支付接口，获取支付结果
                        String result = alipay.pay(orderInfo, true);

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        });
    }

    private void weixinGo() {
        Request request = new Request.Builder().
                url(Server.GET_PAY_ORDERID + "?money=" + 100 * Integer.valueOf(tvCount.getText().toString())
                        + "&type=wxpay").
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(CzActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                orderID = response.body().string();
                weixinPay();
            }
        });
    }

    private void weixinPay() {
        final Request request = new Request.Builder().
                url(" "
                        + "?payid=wxpay&type=wxpay"
                        + "&order_id=" + orderID
                        + "&appid=dongyijs" + "&total=" + 100 * Integer.valueOf(tvCount.getText().toString())).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(CzActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    final JSONObject res = new JSONObject(response.body().string());
                    final PayReq payReq = new PayReq();
                    payReq.appId = WX_APP_ID;
                    payReq.partnerId = res.getString("partnerid");
                    payReq.prepayId = res.getString("prepayid");
                    payReq.packageValue = res.getString("package");
                    payReq.nonceStr = res.getString("noncestr");
                    payReq.timeStamp = res.getString("timestamp");
                    payReq.sign = res.getString("sign");
                    payReq.extData = "app data";
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            super.onPostExecute(aVoid);
                            api.sendReq(payReq);
                        }
                    }.execute();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void cardGo() {
        String pwd = editCard.getText().toString();
        if (pwd.equals("")) {
            Toast.makeText(CzActivity.this, "充值卡密码不能为空", Toast.LENGTH_SHORT).show();
        } else {
            Request request = new Request.Builder().
                    url(Server.RECHARGE + "?phone_data=" + getPrefs().getString("phone", "")
                            + "&password_data=" + pwd).
                    build();
            OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    OkHttpManager.backgroundThreadShortToast(CzActivity.this, "错误：" + e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    OkHttpManager.backgroundThreadShortToast(CzActivity.this, response.body().string());
                }
            });
        }
    }

    private void loadUserInfo() {
        Request request = new Request.Builder().
                url(Server.GET_USER_INFO + "?phone_data=" + getPrefs().getString("phone", "")).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(CzActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final UserInfo userInfo = new Gson().fromJson(response.body().string(), UserInfo.class);
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        tvPhone.setText(getPrefs().getString("phone", ""));
                        tvYue.setText("余额： " + userInfo.getH_u_balance() + "元");
                    }
                }.execute();
            }
        });
    }
}
